﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Resources;
using System.Windows.Controls;

using HexTD.util;

namespace HexTD.UI
{
	public class LevelSelector
	{

		private Context context;
		private HexTD mainApp;
		private List<string[]> levels;
		private ListBox model;
		private string indexUrl;
#if PORT
    private HTMLEditorKit editorkit;
#endif

		/** Creates new form PanelLevelSelector */
		public LevelSelector(ListBox levelListBox)
		{
			this.model = levelListBox;

			this.model.SelectionChanged += new SelectionChangedEventHandler(model_SelectionChanged);

			//this.model.Visibility = System.Windows.Visibility.Collapsed;
			this.levels = new List<string[]>();
#if PORT
        this.editorkit = new HTMLEditorKit();
#endif
		}

		public void setContext(Context c, HexTD mainApp)
		{
			this.context = c;
			this.mainApp = mainApp;

#if PORT
        initComponents();

        StyleSheet s = this.context.loadStyleSheet("styles.css");
        this.editorkit.setStyleSheet(s);
        this.jTextPane_levelInfo.setEditorKit(this.editorkit);
#endif
		}

		private void refillList()
		{
			foreach (string[] i in levels)
			{
				this.model.Items.Add(i[0]);
			}

			if (this.model.Items.Count > 0)
			{
				this.model.SelectedIndex = 0;
			}
		}

		private void selectLevel(int i)
		{
			if (i >= 0 && i < this.levels.Count)
			{
				String[] levelInfo = this.levels[i];
				try
				{
					string levelPath = Path.Combine(this.indexUrl, levelInfo[1]);
					StreamResourceInfo sr = Application.GetResourceStream(new Uri(levelPath, UriKind.Relative));
					context.loadMap(sr.Stream, levelInfo[1]);
				}
				catch (Exception e)
				{
					System.Diagnostics.Debug.WriteLine(e.ToString());
				}
			}
		}

		public void loadIndex(String fileUrl)
		{
			this.levels.Clear();

			try
			{
				StreamResourceInfo sr = Application.GetResourceStream(new Uri(fileUrl, UriKind.Relative));

				using (TextReader tr = new StreamReader(sr.Stream))
				{
					String sLine1, sLine2;

					while ((sLine1 = tr.ReadLine()) != null)
					{
						// Ensure sLine1 is a nonempty string.
						if (sLine1.Trim().Length == 0)
							continue;

						// Ensure sLine2 is a nonempty string.
						sLine2 = tr.ReadLine();
						if ((sLine2 == null) || (sLine2.Trim().Length == 0))
							continue;

						String[] levelInfo = { sLine1, sLine2 };
						this.levels.Add(levelInfo);
					}
				}

				this.indexUrl = Path.GetDirectoryName(fileUrl);
			}
			catch (Exception _ex)
			{
				System.Diagnostics.Debug.WriteLine("HexTD::readFile:: Failed: " + _ex.ToString());
				return;
			}

			this.refillList();
		}

		private void loadNew()
		{
#if PORT
			TextReader b = new TextReader(new StringReader(this.jTextPane1.getText()));
			this.context.loadMap(b, "Custom");
#endif
			this.mainApp.mapChanged();
		}

		public void setLevelInfo(String html)
		{
#if PORT_FEAT
			this.jTextPane_levelInfo.setText(html);
#endif
		}

#if PORT
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jFrame1 = new javax.swing.JFrame();
        jPanel1 = new javax.swing.JPanel();
        jButton_cancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton_load = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton_start = new javax.swing.JButton();
        jButton_new = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextPane_levelInfo = new javax.swing.JTextPane();

        jFrame1.setBackground(Color.FromArgb(255, 0, 0, 0));
        jFrame1.setMinimumSize(new java.awt.Dimension(600, 400));

        jPanel1.setBackground(Color.FromArgb(255, 0, 0, 0));
        jPanel1.setForeground(Color.FromArgb(255, 220, 255, 220));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jButton_cancel.setBackground(Color.FromArgb(255, 0, 0, 0));
        jButton_cancel.setForeground(Color.FromArgb(255, 220, 255, 220));
        jButton_cancel.setText("Cancel");
        jButton_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_cancelActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
        jPanel1.add(jButton_cancel, gridBagConstraints);

        jLabel1.setBackground(Color.FromArgb(255, 0, 0, 0));
        jLabel1.setForeground(Color.FromArgb(255, 220, 255, 220));
        jLabel1.setText("Paste the level definition in the box and click \"Load\".");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 2;
        jPanel1.add(jLabel1, gridBagConstraints);

        jScrollPane2.setViewportView(jTextPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.01;
        gridBagConstraints.weighty = 0.01;
        jPanel1.add(jScrollPane2, gridBagConstraints);

        jButton_load.setBackground(Color.FromArgb(255, 0, 0, 0));
        jButton_load.setForeground(Color.FromArgb(255, 220, 255, 220));
        jButton_load.setText("Load");
        jButton_load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_loadActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        jPanel1.add(jButton_load, gridBagConstraints);

        jFrame1.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        setBackground(context.colors.getColorBackGround());
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select Level", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), context.colors.getColorForeGround()));
        setForeground(context.colors.getColorForeGround());
        setMaximumSize(new java.awt.Dimension(200, 2147483647));
        setMinimumSize(new java.awt.Dimension(200, 25));
        setPreferredSize(new java.awt.Dimension(200, 139));
        setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBackground(context.colors.getColorBackGround());
        jScrollPane1.setForeground(context.colors.getColorForeGround());

        jList1.setBackground(context.colors.getColorBackGround());
        jList1.setForeground(context.colors.getColorForeGround());
        jList1.setModel(this.model);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0E-4;
        gridBagConstraints.weighty = 0.1;
        add(jScrollPane1, gridBagConstraints);

        jButton_start.setBackground(context.colors.getColorBackGround());
        jButton_start.setForeground(context.colors.getColorForeGround());
        jButton_start.setText("Start!");
        jButton_start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_startActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.01;
        add(jButton_start, gridBagConstraints);

        jButton_new.setBackground(context.colors.getColorBackGround());
        jButton_new.setForeground(context.colors.getColorForeGround());
        jButton_new.setText("Load");
        jButton_new.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_newActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.01;
        add(jButton_new, gridBagConstraints);

        jPanel2.setBackground(context.colors.getColorBackGround());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Level Info", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Bitstream Vera Sans", 0, 13), context.colors.getColorForeGround()));
        jPanel2.setForeground(context.colors.getColorForeGround());
        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane3.setBorder(null);

        jTextPane_levelInfo.setBorder(null);
        jScrollPane3.setViewportView(jTextPane_levelInfo);

        jPanel2.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0E-4;
        gridBagConstraints.weighty = 0.05;
        add(jPanel2, gridBagConstraints);
    }// </editor-fold>                        

    private void jButton_loadActionPerformed(java.awt.event.ActionEvent evt) {                                             
        this.loadNew();
        this.jFrame1.setVisible(false);
    }                                            

    private void jButton_cancelActionPerformed(java.awt.event.ActionEvent evt) {                                               
        this.jFrame1.setVisible(false);
    }                                              

    private void jButton_newActionPerformed(java.awt.event.ActionEvent evt) {                                            
        this.jFrame1.pack();
        this.jFrame1.setVisible(true);
    }                                           

    private void jButton_startActionPerformed(java.awt.event.ActionEvent evt) {                                              
        this.mainApp.startLevel();
    }                                             

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {                                    
        this.selectLevel(this.jList1.getSelectedIndex());
    }                                   
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton_cancel;
    private javax.swing.JButton jButton_load;
    private javax.swing.JButton jButton_new;
    private javax.swing.JButton jButton_start;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JTextPane jTextPane_levelInfo;
    // End of variables declaration                   
#endif

		void model_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			this.selectLevel(this.model.SelectedIndex);
		}
	}
}
